package student.aistar.day15.homework01;

public class AccountThreadDemo implements Runnable {
    private Account acc = new Account();
    @Override
    public void run() {
        for(int i = 0; i < 9; i++){
            if(acc.getBalance() > 0){
                withDraw(10);
            }
        }
    }

    //取钱的方法 - 同步方法 - synchronized
    //一次只能一个线程 进入
    private void withDraw(double money) {
        if(acc.getBalance() > 0){
            //开发中优先使用同步代码块
            synchronized (acc){//非静态属性 - 对象锁, 同一个类的对象竞争的是同一把锁锁
                //调用实体类中取钱的方法
                System.out.println(Thread.currentThread().getName() + ".正在取钱...");

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            acc.change(money);
            System.out.println(Thread.currentThread().getName() + ",付款结束,余额为:" + acc.getBalance());
        }
    }
    public static void main(String[] args) {
        //共享资源
        Runnable r = new AccountThreadDemo();
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);

        t1.setName("老婆");
        t2.setName("老公");

        //设置线程的优先级 [1~10]
        //设置线程的优先级,数字[1~10].注意点:数字越大,优先级越高.
        // 但是并不是优先级越高的线程就一定会优先执行.只是希望它先执行.最终还是要cpu的.

        t1.setPriority(Thread.MIN_PRIORITY);
        t2.setPriority(Thread.MAX_PRIORITY);

        t1.start();
        t2.start();
    }
}
